<template>
  <el-dialog :title="title" v-model="dialogVisible" width="80%" :close-on-click-modal="false" append-to-body>
    <h3></h3>
    <div class="music-score-container">
      <div class="score-input">
        <el-input v-model="scoreText" type="textarea" :rows="20" placeholder="请输入乐谱文本格式" @input="handleScoreChange" />
      </div>
      <div class="score-preview">
        <div class="preview-container">
          <div class="preview-content">
            <div v-for="(section, index) in parsedScore" :key="index" class="score-section">
              <!-- 根据需求，注释内容不显示 -->
              <div v-if="section.type === 'lyrics'" class="lyrics-line">
                <template v-for="(item, idx) in section.content" :key="idx">
                  <div v-if="item.chord" style="margin-right: 5px;" class="chord-lyric-container">
                    <div class="chord-container" :style="{ color: item.chordColor }">
                      {{ item.chord }}
                    </div>
                    <!-- 如果文本为空或只有空格，显示正方形 -->
                    <div v-if="item.isEmpty" class="square-placeholder" :style="{ color: item.chordColor }"></div>
                    <span v-else class="lyric-text" :style="{ color: item.chordColor }">{{ item.text }}</span>
                  </div>
                  <span v-else class="lyric-text" style="margin-right: 5px;">{{ item.text }}</span>
                </template>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue';
import { changeSheet } from "@/api/system/sing";
const { proxy } = getCurrentInstance();
const props = defineProps({
  title: {
    type: String,
    default: '乐谱编辑'
  }
});

const emit = defineEmits(['submit']);

const dialogVisible = ref(false);
const scoreText = ref('');
const parsedScore = ref([]);

// 解析乐谱文本
const parseScore = (text) => {
  const lines = text.split('\n').filter(line => line.trim());
  const result = [];

  lines.forEach(line => {
    // 检查是否是注释行 - 以{开头的行
    if (line.includes('{') && line.includes('}')) {
      // 解析注释 - 但根据需求，我们不显示注释内容
      const commentMatch = line.match(/\{([^}]+)\}/);
      if (commentMatch) {
        // 我们仍然解析注释，但在UI中不会显示
        result.push({
          type: 'comment',
          content: commentMatch[1]
        });
      }
    } else {
      // 解析歌词和和弦
      const parts = [];
      let currentText = '';
      let i = 0;

      while (i < line.length) {
        if (line[i] === '[') {
          // 提取和弦
          const chordMatch = line.slice(i).match(/\[([^\]]+)\]/);
          if (chordMatch) {
            // 处理前面的文本
            if (currentText) {
              parts.push({ text: currentText, chord: null });
              currentText = '';
            }

            // 获取和弦后面的文本
            const remainingText = line.slice(i + chordMatch[0].length);
            let nextText = '';
            let j = 0;

            // 检查是否紧跟着另一个和弦
            const hasNextChord = remainingText.trimStart().startsWith('[');

            // 如果紧跟着另一个和弦，nextText保持为空
            // 否则只获取下一个字符（和旋只对后面的一个字符生效）
            if (!hasNextChord) {
              // 跳过前导空白字符
              while (j < remainingText.length && remainingText[j].trim() === '') {
                nextText += remainingText[j];
                j++;
              }
              // 只添加一个非空白字符
              if (j < remainingText.length) {
                nextText += remainingText[j];
                j++;
              }
            } else {
              // 如果紧跟着另一个和弦，只需跳过空白字符
              j = remainingText.search(/\S/);
              if (j === -1) j = remainingText.length; // 如果全是空白字符
            }

            // 检查文本是否为空或只有空格
            const isEmpty = nextText.trim() === '';

            // 添加和弦和对应文本
            parts.push({
              text: nextText,
              chord: chordMatch[1],
              // 为1-7的和弦分配彩虹色
              chordColor: getChordColor(chordMatch[1]),
              // 标记是否为空文本
              isEmpty: isEmpty
            });

            // 更新索引
            if (!hasNextChord) {
              i += chordMatch[0].length + nextText.length;
            } else {
              // 如果是连续和弦，只更新到下一个和弦的开始位置
              i += chordMatch[0].length + j;
            }
            continue;
          }
        }
        currentText += line[i];
        i++;
      }

      if (currentText) {
        [...currentText].forEach((char) => {
          parts.push({ text: char, chord: null });
        });
        // parts.push({ text: currentText, chord: null });
      }

      result.push({
        type: 'lyrics',
        content: parts
      });
    }
  });

  return result;
};

// 根据和弦数字返回对应的彩虹色
const getChordColor = (chord) => {
  // 提取和弦中的数字
  const chordNum = chord.match(/\d/);
  if (!chordNum) return '#ffffff'; // 默认白色

  // 彩虹色映射表 (1-7对应七种颜色)
  const colorMap = {
    '1': '#FF0000', // 红
    '2': '#FF7F00', // 橙
    '3': '#FFFF00', // 黄
    '4': '#00FF00', // 绿
    '5': '#0000FF', // 蓝
    '6': '#4B0082', // 靛
    '7': '#9400D3'  // 紫
  };

  return colorMap[chordNum[0]] || '#ffffff';
};

// 监听文本变化
watch(scoreText, (newValue) => {
  parsedScore.value = parseScore(newValue);
});

// 处理乐谱文本变化
const handleScoreChange = () => {
  parsedScore.value = parseScore(scoreText.value);
};
let singId = null
// 处理提交
const handleSubmit = () => {
  
  console.log("🚀 ~ handleSubmit ~ singId:", singId)
  if (singId === null) {
    proxy.$modal.msgError("数据出错");
    return
  }
  changeSheet(singId, scoreText.value).then(response => {
    if (response.code !== 200) {
      proxy.$modal.msgError(response.msg);
      return;    
    }
    proxy.$modal.msgSuccess("修改成功");
    emit('submit');
    dialogVisible.value = false;
  });
};

const showDialog = (id, text) => {
  console.log("🚀 ~ showDialog ~ singId, text:", id, text)
  singId = id;
  scoreText.value = text;
  dialogVisible.value = true;
};
// 对外暴露方法
defineExpose({
  showDialog
});
</script>

<style scoped>
.music-score-container {
  display: flex;
  gap: 20px;
  height: 600px;
}

.score-input {
  flex: 1;
  height: 100%;
}

.score-preview {
  flex: 1;
  height: 100%;
  background-color: #1a1a1a;
  border-radius: 8px;
  padding: 20px;
  color: #fff;
}

.preview-container {
  height: 100%;
  overflow-y: auto;
}

.preview-content {
  font-family: Arial, sans-serif;
}

.score-section {
  margin-bottom: 16px;
}

.comment-text {
  color: #888;
  font-size: 14px;
  margin-bottom: 8px;
}

.lyrics-line {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 8px;
  height: 50px;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.chord-lyric-container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  margin-right: 4px;
  position: relative;
}

.chord-container {
  font-size: 14px;
  font-weight: bold;
  line-height: 1;
  margin-bottom: 2px;
}

.lyric-text {
  color: #fff;
}

/* 正方形占位符样式 */
.square-placeholder {
  width: 16px;
  height: 16px;
  background-color: currentColor;
  opacity: 0.7;
  display: inline-block;
  margin-top: 2px;
}

/* 确保和弦、文字和正方形对齐 */
.chord-lyric-container {
  min-width: 16px;
  text-align: center;
}
</style>